#include "random_in.h"

/* 熵池，128字，既 512字节 */
static uint32_t entropy_pool[ENTROPY_POOL_LEN_WORDS];

// 8字数组
static const uint32_t table[8] = {
    0x0, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
    0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278};

static void _entropy_pool_update(uint32_t g, int j)
{
    uint32_t temp = g ^ entropy_pool[j];
    temp ^= entropy_pool[(j+1)% ENTROPY_POOL_LEN_WORDS];
    temp ^= entropy_pool[(j+25)% ENTROPY_POOL_LEN_WORDS];
    temp ^= entropy_pool[(j+51)% ENTROPY_POOL_LEN_WORDS];
    temp ^= entropy_pool[(j+103)% ENTROPY_POOL_LEN_WORDS];
    temp = (temp >> 3) ^ table[temp & 7];
    entropy_pool[j] = temp;
}

/**
 * @brief 更新熵池
 * 
 * @param g 熵数据
 * @param len 长度
 * @return int 成功返回0，或错误码
 */
int entropy_pool_update(uint32_t* g, const int len)
{
    if(!g || len < 1) return EINVAL;

    for (int i = 0; i < len; i++)
        _entropy_pool_update(g[i], i);
    return 0;
}

/**
 * @brief Get the entropy pool object
 * 
 * @return unsigned* 
 */
unsigned char* get_entropy_pool()
{
    return (unsigned char*)entropy_pool;
}